package com.chucang.shucang.oms.listener;

import cn.hutool.core.bean.BeanUtil;
import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.common.mq.to.BlindBoxOrderBaseTO;
import com.chucang.shucang.common.mq.to.CollectionOrderBaseTO;
import com.chucang.shucang.oms.constant.OmsCommonConstant;
import com.chucang.shucang.oms.entity.BlindBoxOrderBaseEntity;
import com.chucang.shucang.oms.entity.CollectionOrderBaseEntity;
import com.chucang.shucang.oms.service.BlindBoxOrderBaseService;
import com.chucang.shucang.oms.service.CollectionOrderBaseService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/12 15:53
 * @description
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RabbitListener(queues = RabbitConstant.ORDER_PANIC_PURCHASE_QUEUE)
public class PanicPurchaseOrderListener {

    private final CollectionOrderBaseService collectionOrderBaseService;
    private final BlindBoxOrderBaseService blindBoxOrderBaseService;

    @RabbitHandler
    public void collectionOrderListener(CollectionOrderBaseTO collectionOrderBase, Channel channel, Message message) throws IOException {
        log.info("获取到藏品订单信息！");
        try {
            //处理藏品订单
            CollectionOrderBaseEntity orderBaseEntity = new CollectionOrderBaseEntity();
            BeanUtil.copyProperties(collectionOrderBase, orderBaseEntity);
            orderBaseEntity.setStatus(OmsCommonConstant.WAITING_FOR_PAY);
            collectionOrderBaseService.save(orderBaseEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("藏品订单处理异常！");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void blindBoxOrderListener(BlindBoxOrderBaseTO blindBoxOrderBase, Channel channel, Message message) throws IOException {
        log.info("获取到盲盒订单信息！");
        try {
            //处理盲盒订单
            BlindBoxOrderBaseEntity orderBaseEntity = new BlindBoxOrderBaseEntity();
            BeanUtil.copyProperties(blindBoxOrderBase, orderBaseEntity);
            blindBoxOrderBaseService.save(orderBaseEntity);
            orderBaseEntity.setStatus(OmsCommonConstant.WAITING_FOR_PAY);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("盲盒订单处理异常");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
